package cn.xd.itstack.springframework.aop.framework;

import cn.xd.itstack.springframework.aop.AdvisedSupport;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Classname JdkDyamicAopProxy
 * @Description TODO
 * @Date 2022/6/4 下午5:25
 * @Created by lvxiaodong
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

     private AdvisedSupport advisedSupport;


     public JdkDynamicAopProxy(AdvisedSupport advisedSupport){
         this.advisedSupport = advisedSupport;
     }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),advisedSupport.getTargetResource().getTargetClass(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
         if(advisedSupport.getMethodMatcher().matches(advisedSupport.getTargetResource().getTarget().getClass(),method)){
             MethodInterceptor methodInterceptor = advisedSupport.getMethodInterceptor();
             return methodInterceptor.invoke(new ReflectiveMethodInvocation(advisedSupport.getTargetResource().getTarget(), method, args));
         }
        return method.invoke(advisedSupport.getTargetResource().getTarget(),args);
    }
}
